<template>
  <div class="app-container">

    <div class="handle-box">
      <span style="margin-right: 10px">{{ $t("area.Layer") }}</span>
      <treeselect
        v-model="mapValue"
        :placeholder="$t('operating.pleaseChosen')"
        :max-height="600"
        style="width: 150px"
        :options="maps"
      />

      <span style="margin: 0px 10px">{{ $t("heatChart.resourceType") }}</span>
      <el-select v-model="resourceType" size="small" style="width: 100px">
        <el-option
          v-for="item in resourceTypes"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>

      <span style="margin: 0px 10px">{{ $t("operating.searchDate") }}</span>
      <el-date-picker
        v-model="dateValue"
        size="small"
        type="datetimerange"
        :start-placeholde="$t('operating.StartTime')"
        :end-placeholde="$t('operating.EndTime')"
        value-format="yyyy-MM-dd HH:mm:ss"
        :clearable="false"
        :picker-options="this.v_DateTimePickerOptions"
        style="width: 350px"
      />

      <el-button
        icon="el-icon-search"
        size="mini"
        style="margin-left: 10px; background-color: #f1a11e; color: #fff"
        @click="searchHistoryData"
      >{{ $t("operating.search") }}</el-button>
      <el-button
        type="primary"
        style="margin-left: 10px"
        size="mini"
        @click="checkHistorySearch"
      >{{ $t("history.checkHistorySearch") }}</el-button>
      <div v-show="show" class="radiusSlider">
        <span style="margin: 0px 10px">{{ $t("heatChart.radiusSlider") }}</span>
        <el-slider
          v-model="radiusIndex"
          :max="20"
          :min="1"
          :format-tooltip="formatTooltip"
          @change="changeRadiusSlider"
        />
      </div>
    </div>
    <div
      v-show="show"
      id="mapbox"
      ref="mapbox"
      :style="{ height: mapHeight, width: mapWidth }"
    >
      <!-- 地图容器 -->
      <div id="map" :style="{ height: mapHeight, width: mapWidth }" />
      <div class="positiondiv"><span /></div>
      <div class="scalediv"><span /></div>
    </div>
    <el-table v-show="!show" style="margin-top:15px" class="historyList" :data="tableHistoryData">
      <el-table-column
        prop="mapName"
        :label="$t('heatChart.mapName')"
        min-width="150"
      />
      <el-table-column
        prop="startTime"
        :label="$t('heatChart.startTime')"
        min-width="200"
      />
      <el-table-column
        prop="endTime"
        :label="$t('heatChart.endTime')"
        min-width="200"
      />
      <el-table-column :label="$t('operating.operating')">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="againCheckHistory(scope.$index, scope.row)"
          >{{ $t("history.againCheckHistory") }}</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
// import ol from "openlayers";
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { baseUrl } from '@/utils/global'
import {
  Tile as TileLayer,
  Image,
  Heatmap
} from 'ol/layer.js'
import { OSM, Vector, ImageStatic } from 'ol/source.js'
import { Circle, LineString, Point, Polygon } from 'ol/geom.js'
import Feature from 'ol/Feature.js'
import 'ol/ol.css'
import {
  getPosDataEx,
  getMap,
  getMapTree,
  getHistorySearchInfo
} from '@/api/cy.js'
import {
  Load_Map,
  Load_Fence,
  _TransPixel,
  TagStyle,
  _dPR,
  _iMap,
  t,
  FenceLayer,
  FenceSource
} from '@/utils/iMap.js'

export default {
  components: { Treeselect },
  data() {
    return {
      /** ***********显示相关************/
      mapValue: null, // 地图选择的值
      maps: [], // 地图列表
      dateValue: '', // 开始日期控件值
      datas: [],
      radiusIndex: 5,

      tableHistoryData: [], // 显示的历史搜索条件的列表数据容器
      show: false, // 控制搜索历史表格是否显示
      /** ***********显示相关************/
      mapHeight: window.innerHeight - 180, // 地图区域高度
      mapWidth: window.innerWidth - 220,
      //  **************地图相关参数**************  //
      HeatmapLayer: null, // 热力图图层
      HeatmapSource: null, // 热力图资源容器

      curr_page: 1, // 当前页数
      total_pages: 1, // 总页数
      page_datanum: 10, // 每页返回的数据条数，1分钟的数据为一条

      resourceType: 'all',
      resourceTypes: [
        { value: 'all', label: this.$t('heatChart.all') },
        { value: 'staff', label: this.$t('realtime.staff') },
        { value: 'car', label: this.$t('realtime.car') },
        { value: 'material', label: this.$t('realtime.material') }
      ]
    }
  },

  // 钩子
  mounted() {
    const self = this
    this.setQueryTime()

    self.windowRefresh()

    window.onresize = function temp() {
      self.windowRefresh()
    }

    this.init()
  },

  methods: {
    /**
     * 查看搜索记录
     */
    checkHistorySearch() {
      this.show = false
      this.tableHistoryData = []
      this.getHistorySearchInfo()
    },

    formatTooltip(val) {
      return val
    },

    changeRadiusSlider(val) {
      if (this.HeatmapLayer != null) {
        this.HeatmapLayer.setRadius(parseInt(val))
      }
    },

    // 搜索历史数据
    searchHistoryData() {
      this.show = true
      this.radiusIndex = 5 // 初始化热圈半径

      this.startDate = this.v_FormatDateTime(this.dateValue[0])
      this.endDate = this.v_FormatDateTime(this.dateValue[1])

      if (this.mapValue === '' || this.mapValue === null) {
        this.v_MyMessage(this.$t('Notice.pleaseSelectALayerFirst'), 'warning')
      } else {
        /* 1、获取地图信息，并初始化地图*/
        getMap(this.mapValue).then((res) => {
          const RES = this.responseUse(res)
          Load_Map(
            baseUrl + RES.mapPath,
            RES.mapActualX,
            RES.mapActualY,
            RES.mapPixelX,
            RES.mapPixelY,
            RES.mapPixelX / RES.mapActualX,
            [RES.mapOriginX, RES.mapOriginY]
          )

          this.getThermodynamicData()
        })
      }
    },

    /**
     * 获取热力图数据
     */
    getThermodynamicData() {
      const param = {
        pageNum: this.curr_page, // 当前第多少也
        pageSize: this.page_datanum, // 每页数据条数
        param: {
          layerId: parseInt(this.mapValue), // 地图ID
          resourceType: this.resourceType === 'all' ? '' : this.resourceType, // 资源类型
          startTime: this.startDate, // 开始时间
          endTime: this.endDate, // 结束时间
          enableLog: true // 告诉后端此条搜索是否需要进行记录
        }
      }
      // 清除热力图数据
      this.clearThermodynamicData()

      // this.datas.splice(0); // 清空数据
      this.datas = []

      getPosDataEx(param).then((res) => {
        const RES = this.responseUse(res)
        this.datas = RES

        /** ************************debug cao**************************/
        if (this.datas !== null) {
          let count = 0
          for (let i = 0; i < this.datas.length; i++) {
            count = count + this.datas[i].count
          }
          console.log(
            '原始数据量：',
            count,
            '--聚合数据长度：',
            this.datas.length
          )
          /** ************************debug cao**************************/
        }

        this.loadThermodynamicData()
      })
    },

    clearThermodynamicData() {
      const self = this
      // 清除热力图数据
      if (self.HeatmapSource != null) {
        self.HeatmapSource.forEachFeature(function(feature) {
          self.HeatmapSource.removeFeature(feature)
        })

        self.HeatmapSource = null
      }
      if (self.HeatmapLayer != null) {
        _iMap.removeLayer(self.HeatmapLayer)
        self.HeatmapLayer = null
      }
    },
    /**
     * 将获到的热力图数据加载到地图中
     */
    loadThermodynamicData() {
      const self = this
      const len = self.datas.length

      if (len > 0) {
        if (self.HeatmapSource === null) {
          self.HeatmapSource = new Vector({

          }, {
            dataProjection: 'EPSG:900931',
            featureProjection: 'EPSG:900931'
          })
        }

        self.addThermodynamicChartData({ data: self.datas, max: 1000 })
        if (self.HeatmapLayer === null) {
          self.HeatmapLayer = new Heatmap({
            source: self.HeatmapSource,
            opacity: 1, // 透明度
            blur: 7, // 模糊大小
            radius: 5 // 半径大小
          })

          _iMap.addLayer(self.HeatmapLayer)
        }
      } else {
        self.v_MyMessage(self.$t('Notice.noHeatMapData'), 'warning')
      }
    },

    addThermodynamicChartData(params) {
      const data = params.data
      const max = params.max
      const array = []
      for (let i = 0; i < data.length; i++) {
        const coordinate = [parseFloat(data[i].x), parseFloat(data[i].y)]
        const feature = new Feature({
          geometry: new Point(_TransPixel(coordinate)),
          weight: parseFloat(data[i].count) / parseFloat(max)
        })
        array.push(feature)
      }
      this.HeatmapSource.addFeatures(array)
    },
    /**
     * 根据历史搜索条件进行查询
     */
    againCheckHistory(index, row) {
      this.mapValue = row.layerId
      this.dateValue = []
      this.dateValue.push(new Date(row.startTime))
      this.dateValue.push(new Date(row.endTime))
      this.searchHistoryData()
    },

    // 初始化函数
    init: function() {
      const self = this

      // 获取地图列表
      getMapTree().then((res) => {
        const RES = this.responseUse(res)
        self.maps = RES
      })

      this.getHistorySearchInfo()
    },

    // 获取历史搜索记录
    getHistorySearchInfo() {
      const param = {
        pageNum: '1',
        pageSize: '10',
        param: {
          model: 'heatmap'
        }
      }
      getHistorySearchInfo(param).then((res) => {
        const RES = this.responseUse(res)
        if (RES.content.length > 0) {
          for (let i = 0; i < RES.content.length; i++) {
            this.tableHistoryData.push(RES.content[i].searchValueMap)
          }
        }
      })
    },

    // 刷新窗口
    windowRefresh: function() {
      this.mapHeight = window.innerHeight - 180 + 'px'
      this.mapWidth = window.innerWidth - 220 + 'px'
    },

    // 设置查询时间
    setQueryTime() {
      const myDate = new Date()
      const year = myDate.getFullYear()
      const month = myDate.getMonth()
      const day = myDate.getDate()
      this.dateValue = [
        new Date(year, month, day, '08', '00', '00'),
        new Date(year, month, day, '18', '00', '00')
      ]
    }
  }
}
</script>
<style>
.radiusSlider .el-slider__runway {
  margin: 14px 0;
}
</style>

<style scoped>
#body {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

#mapbox {
  background-color: #fff;
  vertical-align: middle;
  background-color: #fff;
  width: auto;
  overflow: auto;
}

.el-table__row .cell {
  white-space: pre-line;
}

.radiusSlider {
  width: 220px;
  position: absolute;
  right: 20px;
  top: 12px;
}
.radiusSlider span {
  line-height: 38px !important;
}
.el-slider {
  width: 150px;
  float: right;
}

.handle-box {
  width: 100%;
}

.handle-box * {
  float: left;
}
.handle-box span {
  line-height: 32px;
}

.list-title {
  margin-left: 300px;
  font-size: 20px;
  font-weight: 800;
}
</style>
